import os
import uuid
import requests
import BaseHandler


# API: /bk/api/editor/upload
# Neditor上传图片功能
class ApiEditorUploadHandler(BaseHandler):
    def post(self):
        upload_dir = os.path.realpath(os.path.join(
            os.path.dirname(__file__), "../../static/uploads/test"))
        # 如果不存在uploads目录则创建
        if not os.path.exists(upload_dir):
            os.makedirs(upload_dir)
        random_name = str(uuid.uuid4())
        # 接收的名字可以在neditor.config.js中定义
        file_data = self.request.files["file"][0]
        original_name = file_data['filename']
        extension = os.path.splitext(original_name)[1].lower()
        final_name = random_name + extension
        final_path = os.path.join(upload_dir, final_name)
        output_file = open(final_path, 'wb')
        output_file.write(file_data['body'])

        relative_path = "/static/uploads/test/%s" % (final_name)
        self.write({'code': 200, 'url': relative_path})
        # without this header IE non-drag/drop upload will fail
        self.set_header("Content-Type", "text/plain")


# API: /bk/api/catcher/upload
# Neditor上传百度搜索到的图片功能
class ApiCatcherUploadHandler(BaseHandler):
    def post(self):
        upload_dir = os.path.realpath(os.path.join(
            os.path.dirname(__file__), "../../static/uploads/editor"))
        # 如果不存在uploads目录则创建
        if not os.path.exists(upload_dir):
            os.makedirs(upload_dir)
        image_urls = self.get_arguments('upfile[]')
        path_list = []
        for img_url in image_urls:
            img = requests.get(img_url).content
            random_name = str(uuid.uuid4())
            extension = os.path.splitext(img_url)[1].lower()
            final_name = random_name + extension
            final_path = os.path.join(upload_dir, final_name)
            output_file = open(final_path, 'wb')
            output_file.write(img)
            output_file.close()

            img_dict = {}  # 查看neditor.all.js中可以看到需要的格式
            img_dict['source'] = img_url
            img_dict['state'] = "SUCCESS"
            img_dict['url'] = "/static/uploads/editor/%s" % (final_name)
            path_list.append(img_dict)
        self.write({'code': 200, 'list': path_list})
        # without this header IE non-drag/drop upload will fail
        self.set_header("Content-Type", "text/plain")


# API: /bk/api/save/content
class ApiSaveEditorHandler(BaseHandler):
    def post(self):
        self.write({'code': 'ok'})
